﻿using Aker.DevTeam;
using Aker.Product;
using Aker.Properties;
using Aker.Uretim;
using DevExpress.Utils.Paint;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Aker
{
    public partial class Products : XForm
    {
        List<int> selectedProducts = new List<int>();

        string imageBackupPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AkerPhotos";


        public Products()
        {
            InitializeComponent();
        }

        string list = "";
        public Products(string list)
        {
            InitializeComponent();
            this.list = list;
        }


        string[] orderedColumns = new string[] {"Select",
                                                    "Order",
                                                    "PrintCount",
                                                    "ProductId",
                                                    "Thumbnail",
                                                    "Article",
                                                    "PartiNo",
                                                    "Design",
                                                    "Weight",
                                                    "ToleranceWeight",
                                                    "Width",
                                                    "ToleranceWidth",
                                                    "Composition",
                                                    //"CO",
                                                    "ToleranceComposition",
                                                    "Qty",
                                                    "RollCount",                                                    
                                                    "PriceDollar",
                                                    "PriceEuro",
                                                    "Price2Dollar",
                                                    "Price2Euro",
                                                    "Price3Dollar",
                                                    "Price3Euro",
                                                    "Maliyet",
                                                    "FiyatExtra"
                                                    };


        void Products_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            //lbl1.Text = Language.Product.Article;

            btnAdd.ToolTip = "Artikeli ekle";
            btnClear.ToolTip = "Filtreyi temizle";
            btnSelectVisible.ToolTip = "Görünenleri seç";
            btnUpdatePrices.ToolTip = "Fiyat güncelleyici";

            if (!Directory.Exists(imageBackupPath))
            {
                Directory.CreateDirectory(imageBackupPath);
            }

            this.Cursor = Cursors.WaitCursor;

            Data.TAM.HammaddeTableAdapter.Fill(Data.DB.Hammadde);
            this.Cursor = Cursors.WaitCursor;


            gcProduct.Enabled = false;

            //Data.FillProducts();

            if (Data.IsLookupInitialized)
                Data_LookupsLoaded();
            else
                Data.LookupInitialized += Data_LookupsLoaded;



            //AppSession.MainForm.timer.Enabled = true;


            //if (!Data.DB.Product.Columns.Contains("CO"))
            //    Data.DB.Product.Columns.Add("CO", typeof(string));

            //foreach (AkerDB.ProductRow pr in Data.DB.Product.Rows)
            //{
            //    if (!pr.IsCompositionNull())
            //    {
            //        string c = pr.Composition.ToStringNN();
            //        c = c.Replace(" ", "");

            //        if (!c.StartsWith("%"))
            //            c = c.Replace("%", " %");
            //        c = c.Replace("-", " - ");
            //        c = c.Replace("İ", "I");
            //        c = c.Replace("  ", " ");

            //        pr["CO"] = c;
            //    }
            //}

            this.BarcodeRead += Products_BarcodeRead;





            this.Cursor = Cursors.Default;

        }

        void Data_LookupsLoaded()
        {
            Data.ModifiedProducts.Clear();

            gvProduct.Init(Data.DB.Product);

            //gvProduct.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvProduct.AddSummary();
            gvProduct.FormatAsNumber("PriceDollar", "PriceEuro", "Price2Dollar", "Price2Euro", "Price3Dollar", "Price3Euro", "Qty", "FiyatExtra", "Maliyet");
            gvProduct.MakeColumnsReadOnly("ProductId", "Select", "Order", "PriceEuro", "Price2Euro", "Price3Euro", "Qty", "RollCount");


            Data.TAM.SettingTableAdapter.Fill(Data.DB.Setting);

            //string ekstraCarpan = Data.DB.Setting.FindBySettingId(16).Value;

            ////orderedColumns = new string[] { "CO", "Composition" };
            //gvProduct.SetVisibleIndex(orderedColumns);

            if (AppSession.Language == "TR")
            {
                gvProduct.SetCaptions("ToleranceWeight:Ağırlık Tol.", "PrintCount:Kopya", "ToleranceWidth:En Tol.", "ToleranceComposition:Karışım Tol.", "PriceDollar:Fiyat ($)", "PriceEuro:Fiyat (€)", "Price2Dollar:Acenta ($)"
                                    , "Price2Euro:Acenta (€)", "Price3Dollar:Fuar ($)", "Price3Euro:Fuar (€)", "Qty:Stok (mt)", "RollCount:Top Adedi", "Select:Seç", "Order:Sıra", "ProductId:ID", "Article:Artikel", "Desing:Desen", "Weight:Ağırlık", "Width:En", "Composition:Karışım", "FiyatExtra:Fiyat*");// (" + ekstraCarpan + ")");
            }
            else
            {
                gvProduct.SetCaptions("ToleranceWeight:Weight Tol.", "PrintCount:Copy", "ToleranceWidth:Width Tol.", "ToleranceComposition:Comp. Tol.", "PriceDollar:Price ($)", "PriceEuro:Price (€)", "Price2Dollar:Agency ($)"
                                    , "Price2Euro:Agency (€)", "Price3Dollar:Fair ($)", "Price3Euro:Fair (€)", "Qty:Stock (mt)", "RollCount:Roll Count", "FiyatExtra:Fiyat*");
            }


            GridMenu gmProduct = GridManager.GetManager(gvProduct).GridMenu;

            gmProduct.AddMenu("Fotoğraf çek", TakePhoto);
            gmProduct.AddMenu("Seçililerin etiketlerini yazdır", Print_ProductLabel);
            gmProduct.AddMenu("Topları oluştur ve etiketlerini yazdır", CreateRollsAndPrintLabels);
            gmProduct.AddMenu("Top bilgilerini göster", ShowRolls);


            gmProduct.AddMenu("Tümünü seç", SelectAll, true);
            gmProduct.AddMenu("Seçimi temizle", DeselectAll);
            gmProduct.AddMenu("Seçime ekle", AddToSelection);
            gmProduct.AddMenu("Seçimden çıkar", RemoveFromSelection);

            gmProduct.AddMenu("Üretim Siparişi oluştur", CreatePOrder, Resources.newPencil, true);
            gmProduct.AddMenu("İmalat Kartı", ImalatKarti, Resources.Card);
            gmProduct.AddMenu("Sentez Detayı", ShowSentezDetail, Resources.s);

            gvProduct.BestFitColumns();

            gvProduct.RowCellClick += gvProduct_RowCellClick;

            gvProduct.CellValueChanged += gvProduct_CellValueChanged;


            gvProduct.ValidateRow += gvProduct_ValidateRow;
            gvProduct.RowUpdated += gvProduct_RowUpdated;

            gvProduct.InvalidRowException += gvProduct_InvalidRowException;
            gvProduct.RowStyle += gvProduct_RowStyle;

            gvProduct.RowCellStyle += gvProduct_RowCellStyle;

            gvProduct.OptionsView.ShowAutoFilterRow = false;
            RepositoryItemSpinEdit ri = new RepositoryItemSpinEdit();
            ri.IsFloatValue = false;


            Data.TAM.KullaniciTableAdapter.Fill(Data.DB.Kullanici);

            gvProduct.CustomColumnDisplayText += gvProduct_CustomColumnDisplayText;
            gvProduct.CustomDrawCell += gvProduct_CustomDrawCell;
            gvProduct.Columns["PrintCount"].ColumnEdit = ri;



            if (list != "")
            {
                string filter = "[ProductId] In  (" + list + ")";
                gvProduct.ActiveFilterString = filter;
                btnSelectVisible.PerformClick();
                Print_ProductLabel(null, null);
            }
            else
            {
                if (!AppSession.IsOnline)
                    XtraMessageBox.Show(Language.Product.Offline, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            foreach (Control ctrl in splitter.Panel1.Controls)
            {
                if (ctrl.GetType() == typeof(TextEdit))
                    ((TextEdit)ctrl).EditValueChanged += txtArticle_EditValueChanged;
            }

            //    chkPrices.Properties.Items[0].CheckState = CheckState.Checked;

            if (AppSession.UserInfo.YetkiId == 1)
            {
                gvProduct.MakeReadOnly("PrintCount", "Order", "Qty", "RollCount");
                chkPrices.Properties.Items[0].CheckState = CheckState.Unchecked;
                chkPrices.Visible = false;
                btnUpdatePrices.Visible = false;
                btnAdd.Visible = false;

                gmProduct.RemoveMenu(Language.Product.TakePhoto);
                gmProduct.RemoveMenu(Language.Product.CreateRollPrint);
            }
            else if (AppSession.UserInfo.YetkiId == 2)
            {
                chkPrices.Properties.Items[0].CheckState = CheckState.Unchecked;
                chkPrices.Visible = false;
                btnUpdatePrices.Visible = false;
            }
            else if (AppSession.UserInfo.YetkiId == 3)
            {
                gvProduct.MakeReadOnly("PrintCount", "Order", "PriceDollar", "PriceEuro", "Price2Dollar", "Price2Euro", "Price3Dollar", "Price3Euro");
                btnAdd.Visible = false;
                gmProduct.RemoveMenu(Language.Product.TakePhoto);
                gmProduct.RemoveMenu(Language.Product.CreateRollPrint);
            }
            else if (AppSession.UserInfo.YetkiId == 4)
            {
                gvProduct.MakeReadOnly("PrintCount", "Order", "Price2Dollar", "Price2Euro", "Price3Dollar", "Price3Euro");
                btnAdd.Visible = false;
                gmProduct.RemoveMenu(Language.Product.TakePhoto);
                gmProduct.RemoveMenu(Language.Product.CreateRollPrint);
            }


            int type = UserSettings.PriceType;

            gvProduct.SetVisibleIndex(orderedColumns);

            if (AppSession.UserInfo.YetkiId != 5)
            {
                gvProduct.Columns["Maliyet"].Visible = false;
                gvProduct.MakeColumnsReadOnly("FiyatExtra");
                btnMaliyet.Visible = false;
            }


            switch (type)
            {
                case 0:

                    gvProduct.Columns["PriceDollar"].Visible = gvProduct.Columns["PriceEuro"].Visible = true;
                    gvProduct.Columns["Price2Dollar"].Visible = gvProduct.Columns["Price2Euro"].Visible = false;
                    gvProduct.Columns["Price3Dollar"].Visible = gvProduct.Columns["Price3Euro"].Visible = false;
                    break;
                case 1:
                    gvProduct.Columns["PriceDollar"].Visible = gvProduct.Columns["PriceEuro"].Visible = false;
                    gvProduct.Columns["Price2Dollar"].Visible = gvProduct.Columns["Price2Euro"].Visible = true;
                    gvProduct.Columns["Price3Dollar"].Visible = gvProduct.Columns["Price3Euro"].Visible = false;
                    break;
                case 2:
                    gvProduct.Columns["PriceDollar"].Visible = gvProduct.Columns["PriceEuro"].Visible = false;
                    gvProduct.Columns["Price2Dollar"].Visible = gvProduct.Columns["Price2Euro"].Visible = false;
                    gvProduct.Columns["Price3Dollar"].Visible = gvProduct.Columns["Price3Euro"].Visible = true;
                    break;
            }

            gcProduct.Enabled = true;
        }


        private void ShowRolls(object sender, EventArgs e)
        {
            gvProduct.EndEditing();

            selectedProducts.Clear();
            foreach (DataRow dr in Data.DB.Product.Select("Order > 0"))
                selectedProducts.Add((int)dr["ProductId"]);

            if (selectedProducts.Count == 0)
            {
                XtraMessageBox.Show(Language.Product.NoSelection, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            AppSession.MainForm.ShowMdiChildForm(typeof(ArtikelStokVeCikis), selectedProducts.ToArray());
        }

        void gvProduct_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if (e.Column.FieldName == "Qty")
                {
                    int qty = e.CellValue.ToIntNN();
                    if (qty > 0)
                    {
                        //e.Appearance.BackColor = Color.Green;
                        //e.Appearance.ForeColor = Color.White;
                    }
                    else
                        e.Appearance.BackColor = Color.Peru;
                }
        }

        private void CreateRollsAndPrintLabels(object sender, EventArgs e)
        {

            gvProduct.EndEditing();

            selectedProducts.Clear();
            foreach (DataRow dr in Data.DB.Product.Select("Order > 0"))
                selectedProducts.Add((int)dr["ProductId"]);

            if (selectedProducts.Count == 0)
            {
                XtraMessageBox.Show(Language.Product.NoSelection, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DataSet dsReport = Data.DM.ExecuteDataSet("GetProductReport", string.Join(",", selectedProducts));

            dsReport.Tables[0].Columns.Add("Sira", typeof(int));
            dsReport.Tables[0].Columns.Add("PrintCount", typeof(int));


            ProductReportSettings settings = new ProductReportSettings();
            settings.copyCount.Enabled = false;
            if (settings.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                int emptyCount = Convert.ToInt32(settings.emptyCount.Value);


                DataSet dsFinal = dsReport.Clone();
                DataTable dtFinalArticle = dsFinal.Tables[0];


                dtFinalArticle.Columns.Add("RollId", typeof(int));


                foreach (DataRow drArticle in dsReport.Tables[0].Rows)
                {
                    DataRow productRow = Data.DB.Product.Select("ProductId=" + drArticle["ProductId"])[0];
                    if (settings.ManualOrdered)
                        drArticle["Sira"] = productRow["Order"];
                    else
                        drArticle["Sira"] = productRow["ProductId"];

                    int rollCount = productRow["PrintCount"].ToIntNN();

                    if (rollCount > 0)
                    {
                        for (int i = 0; i < rollCount; i++)
                        {
                            AkerDB.RollRow drRoll = Data.DB.Roll.NewRollRow();
                            drRoll.ProductId = productRow["ProductId"].ToIntNN();
                            Data.DB.Roll.AddRollRow(drRoll);
                            Data.TAM.RollTableAdapter.Update(drRoll);

                            AkerDB.StokLinesRow sl = Data.DB.StokLines.NewStokLinesRow();
                            sl.RollId = drRoll.RollId;
                            Data.DB.StokLines.AddStokLinesRow(sl);
                            Data.TAM.StokLinesTableAdapter.Update(sl);

                            DataRow drArticleRoll = dtFinalArticle.NewRow();
                            drArticleRoll["Sira"] = drArticle["Sira"];
                            drArticleRoll["RollId"] = drRoll.RollId;

                            dtFinalArticle.ImportRow(drArticle);
                            dtFinalArticle.Rows.Add(drArticleRoll);
                        }
                    }
                    else
                    {
                        DataRow drArticleRoll = dtFinalArticle.NewRow();
                        drArticleRoll["Sira"] = drArticle["Sira"];
                        drArticleRoll["RollId"] = "0";

                        dtFinalArticle.ImportRow(drArticle);
                        dtFinalArticle.Rows.Add(drArticleRoll);
                    }
                }

                ProductReport pr = new ProductReport(dsFinal, emptyCount, 1);
                pr.ShowPreview();

                foreach (DataRow dr in Data.DB.Product.Select("PrintCount > 0"))
                    dr["PrintCount"] = 0;
            }
        }


        private void ShowSentezDetail(object sender, EventArgs e)
        {
            if (gvProduct.FocusedRowHandle > -1)
            {
                string article = (string)gvProduct.GetFocusedRowCellValue("Article");
                string partiNo = gvProduct.GetFocusedRowCellValue("PartiNo").ToStringNN();

                //if (partiNo != "" && partiNo != "1")
                //{

                //}

                if (partiNo != "")
                    if (article.Contains("-"))
                        article = article + partiNo;
                    else
                        article = article + "-" + partiNo;

                SentezDetail sd = new SentezDetail(article);
                sd.Show();
            }
        }


        void gvProduct_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            string filterCellText = "";

            switch (e.Column.FieldName)
            {
                case "Article":
                    filterCellText = txtArticle.Text;
                    break;
                case "Design":
                    filterCellText = txtDesign.Text;
                    break;
                case "Weight":
                    filterCellText = txtWeight.Text;
                    break;
                case "ToleranceWeight":
                    filterCellText = txtWeightTol.Text;
                    break;
                case "Width":
                    filterCellText = txtWidth.Text;
                    break;
                case "ToleranceWidth":
                    filterCellText = txtWidthTol.Text;
                    break;
                case "Composition":
                    filterCellText = txtComp.Text;
                    break;
                case "ToleranceComposition":
                    filterCellText = txtCompTol.Text;
                    break;
                case "PriceDollar":
                    filterCellText = txtDollar.Text;
                    break;
                case "PriceEuro":
                    filterCellText = txtEuro.Text;
                    break;
            }


            if (String.IsNullOrEmpty(filterCellText))
                return;

            int filterTextIndex = e.DisplayText.IndexOf(filterCellText, StringComparison.CurrentCultureIgnoreCase);
            if (filterTextIndex == -1)
                return;

            XPaint.Graphics.DrawMultiColorString(e.Cache, e.Bounds, e.DisplayText, filterCellText, e.Appearance, Color.Black, Color.Gold, false, filterTextIndex);
            e.Handled = true;
        }

        void gvProduct_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {
            if (e.ListSourceRowIndex < 0)
                return;

            if (e.Column.FieldName == "ModifiedBy")
            {
                if (e.Value == DBNull.Value || e.Value.ToStringNN() == "")
                    e.DisplayText = "";
                else
                    e.DisplayText = Data.DB.Kullanici.FindByKullaniciId((int)e.Value).KullaniciAdi;
            }
        }

        void Products_BarcodeRead(int Barcode)
        {
            btnClear.PerformClick();

            int rowHandle = gvProduct.LocateByValue("ProductId", Barcode);
            gvProduct.FocusedRowHandle = rowHandle;
            gvProduct.MakeRowVisible(rowHandle);

            //Unselect others
            foreach (int selectedRowHandle in gvProduct.GetSelectedRows())
                gvProduct.UnselectRow(selectedRowHandle);

            //Select read
            gvProduct.SelectRow(rowHandle);
        }

        void TakePhoto(object sender, EventArgs e)
        {
            int rowHandle = gvProduct.FocusedRowHandle;
            int productId = gvProduct.GetFocusedRowCellValue("ProductId").ToIntNN();

            using (CanonTaker ct = new CanonTaker())
            {
                DialogResult dr;

                //ct.LatestImage = Image.FromFile("d:\\" + productId + ".jpg");

                DataTable dt = Data.DM.ExecuteDataTable("GetPhotos", productId);

                if (dt.Rows.Count > 0)
                {
                    DataRow drPhotos = dt.Rows[0];

                    ct.pbOriginal.Image = Image.FromStream(new MemoryStream((byte[])drPhotos["Original"]));

                    if (drPhotos["Big"] != DBNull.Value)
                        ct.pbBig.Image = Image.FromStream(new MemoryStream((byte[])drPhotos["Big"]));
                    if (drPhotos["Email"] != DBNull.Value)
                        ct.pbeMail.Image = Image.FromStream(new MemoryStream((byte[])drPhotos["Email"]));
                    if (drPhotos["Thumbnail"] != DBNull.Value)
                        ct.pbThumbnail.Image = Image.FromStream(new MemoryStream((byte[])drPhotos["Thumbnail"]));
                }

                ct.SetAllignment();


                dr = ct.ShowDialog();

                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    this.Cursor = Cursors.WaitCursor;
                    //byte[] thumb = ct.LatestImage
                    //     .CropFromCenter(1500)
                    //     .Resize(32)
                    //     .Unsharpen()
                    //     .ToJPEG();

                    ct.pbOriginal.Image.Save(imageBackupPath + "\\" + productId + "_original.jpg");
                    ct.pbBig.Image.Save(imageBackupPath + "\\" + productId + "_big.jpg");
                    ct.pbeMail.Image.Save(imageBackupPath + "\\" + productId + "_email.jpg");
                    ct.pbThumbnail.Image.Save(imageBackupPath + "\\" + productId + "_thumbnail.jpg");

                    Data.DM.ExecuteNonQuery("UploadPhoto", productId,
                        ct.pbOriginal.Image.ToJPEG(),
                        ct.pbBig.Image.ToJPEG(),
                        ct.pbeMail.Image.ToJPEG(),
                        ct.pbThumbnail.Image.ToJPEG());

                    //Data.TAM.ProductTableAdapter.Update(gvProduct.GetDataRow(rowHandle));

                    gvProduct.SetRowCellValue(rowHandle, "Thumbnail", ct.pbThumbnail.Image.ToJPEG());
                    //gvProduct.GetDataRow(rowHandle).AcceptChanges();
                    //changeds.Add(rowHandle);

                    this.Cursor = Cursors.Default;
                }
            }
        }

        void ImalatKarti(object sender, EventArgs e)
        {
            DataRow dr = gvProduct.GetFocusedDataRow();
            int productId = dr["ProductId"].ToIntNN();

            int stokKartiTipi = -1; //TODO: bu kısım doluysa gelmeli dr["StokKartiTipi"].ToIntNN();
            string bazArtikel = dr["Article"].ToStringNN();

            if (stokKartiTipi == -1)
                stokKartiTipi = StokKartiTipiSecici.GetStokKartiTipi(bazArtikel);

            if (stokKartiTipi == 1)
                AppSession.MainForm.ShowMdiChildForm(typeof(YeniImalatKarti1), productId, true);
            else if (stokKartiTipi == 2)
                AppSession.MainForm.ShowMdiChildForm(typeof(YeniImalatKarti2), productId, true);
        }

        void Print_ProductLabel(object sender, EventArgs e)
        {
            gvProduct.EndEditing();

            selectedProducts.Clear();
            foreach (DataRow dr in Data.DB.Product.Select("Order > 0"))
                selectedProducts.Add((int)dr["ProductId"]);

            if (selectedProducts.Count == 0)
            {
                XtraMessageBox.Show(Language.Product.NoSelection, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DataSet dsReport = Data.DM.ExecuteDataSet("GetProductReport", string.Join(",", selectedProducts));
            dsReport.Tables[0].Columns.Add("Sira", typeof(int));
            dsReport.Tables[0].Columns.Add("PrintCount", typeof(int));
            dsReport.Tables[0].Columns.Add("RollId", typeof(int));

            ProductReportSettings settings = new ProductReportSettings();
            if (settings.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                int emptyCount = Convert.ToInt32(settings.emptyCount.Value);
                int copyCount = Convert.ToInt32(settings.copyCount.Value);


                foreach (DataRow dr in dsReport.Tables[0].Rows)
                {
                    DataRow[] row = Data.DB.Product.Select("ProductId=" + dr["ProductId"]);
                    if (row.Length > 0)
                    {
                        if (settings.ManualOrdered)
                            dr["Sira"] = row[0]["Order"];
                        else
                            dr["Sira"] = row[0]["ProductId"];

                        dr["PrintCount"] = row[0]["PrintCount"];
                    }
                }

                ProductReport pr = new ProductReport(dsReport, emptyCount, copyCount);
                pr.ShowPreview();
            }
        }

        void gvProduct_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.RowHandle > -1)
            {

                if (e.Column.FieldName == "Select")
                    ToggleSelection(e.RowHandle);
                //else if (e.Column.FieldName == "Thumbnail")
                //{
                //    int productId = (int)gvProduct.GetFocusedRowCellValue("ProductId");
                //    ImageViewer iv = new ImageViewer(productId);
                //    iv.WindowState = FormWindowState.Maximized;
                //    iv.ShowDialog();
                //}
            }
        }

        void SelectAll(object sender, EventArgs e)
        {
            gvProduct.BeginUpdate();

            for (int i = 0; i < gvProduct.DataRowCount; i++)
            {
                bool selected = (bool)gvProduct.GetRowCellValue(i, "Select");
                if (!selected)
                    ToggleSelection(i);
            }

            gvProduct.EndUpdate();
        }

        void DeselectAll(object sender, EventArgs e)
        {
            foreach (DataRow item in Data.DB.Product.Rows)
            {
                item["Select"] = false;
                item["Order"] = DBNull.Value;
            }
        }

        void AddToSelection(object sender, EventArgs e)
        {
            gvProduct.BeginUpdate();

            foreach (int rowHandle in gvProduct.GetSelectedRows())
            {
                bool selected = (bool)gvProduct.GetRowCellValue(rowHandle, "Select");
                if (!selected)
                    ToggleSelection(rowHandle);
            }

            gvProduct.EndUpdate();
        }

        void CreatePOrder(object sender, EventArgs e)
        {
            List<int> productIds = new List<int>();

            foreach (DataRow dr in Data.DB.Product.Select("Order > 0"))
            {
                int copy = dr["PrintCount"].ToIntNN();
                if (copy == -1)
                    copy = 1;

                for (int i = 0; i < copy; i++)
                    productIds.Add(dr["ProductId"].ToIntNN());

                dr["Select"] = false;
                dr["Order"] = DBNull.Value;
            }


            AppSession.MainForm.ShowMdiChildForm(typeof(Uretim.YeniSiparis), productIds);
        }

        void RemoveFromSelection(object sender, EventArgs e)
        {
            gvProduct.BeginUpdate();

            foreach (int rowHandle in gvProduct.GetSelectedRows())
            {
                bool selected = (bool)gvProduct.GetRowCellValue(rowHandle, "Select");
                if (selected)
                    ToggleSelection(rowHandle);
            }

            gvProduct.EndUpdate();
        }

        void gvProduct_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            //e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        void gvProduct_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (e.RowHandle > -1)
                {
                    DataRow dr = gvProduct.GetDataRow(e.RowHandle);
                    int currentProductId = dr["ProductId"].ToIntNN();
                    bool selected = false;
                    if (dr["Select"] != DBNull.Value)
                        selected = (bool)dr["Select"];

                    if (selectedProducts.Contains(currentProductId))
                        e.Appearance.BackColor = Color.AliceBlue;
                    else if (selected)
                        e.Appearance.BackColor = Color.AliceBlue;
                    else if (Data.ModifiedProducts.Contains(currentProductId))
                        e.Appearance.BackColor = Color.LightCoral;

                }
            }
            catch (Exception ex)
            {
                AppSession.MainForm.Info = ex.ToString();
            }
        }

        void ToggleSelection(int rowHandle)
        {
            DataRow drCurrent = gvProduct.GetDataRow(rowHandle);


            bool selected = false;
            try
            {
                selected = (bool)drCurrent["Select"];
            }
            catch
            { }

            gvProduct.SetRowCellValue(rowHandle, "Select", !selected);
            object order = Data.DB.Product.Compute("max(Order)", "");

            if (selected) //ÇIKAR
            {
                int silinenSira = (int)gvProduct.GetRowCellValue(rowHandle, "Order");
                gvProduct.SetRowCellValue(rowHandle, "Order", DBNull.Value);
                foreach (DataRow dr in Data.DB.Product.Select("Order > " + silinenSira.ToString()))
                {
                    dr["Order"] = (int)dr["Order"] - 1;
                }
            }
            else  //EKLE
            {
                if (order == DBNull.Value)
                    order = 1;
                else
                    order = (int)order + 1;

                gvProduct.SetRowCellValue(rowHandle, "Order", order);
            }
            gvProduct.EndEditing();
        }

        void gvProduct_RowUpdated(object sender, RowObjectEventArgs e)
        {
            if (isIgnorable(e.RowHandle))
                return;

            DataRowView dv = e.Row as DataRowView;
            dv.Row["ModifiedBy"] = AppSession.UserInfo.UserId;
            dv.Row["ModifiedOn"] = DateTime.Now;
            Data.SaveProduct(dv.Row);
            changeds.Remove(e.RowHandle);
        }

        void gvProduct_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {

            gvProduct.CellValueChanged -= gvProduct_CellValueChanged;

            if (!"Select PrintCount Order Thumbnail".Contains(e.Column.FieldName) && !changeds.Contains(e.RowHandle))
                changeds.Add(e.RowHandle);

            if (e.Column.FieldName == "PriceDollar")
                SetEuroPrice(e.RowHandle, "PriceEuro", e.Value);
            else if (e.Column.FieldName == "Price2Dollar")
                SetEuroPrice(e.RowHandle, "Price2Euro", e.Value);
            else if (e.Column.FieldName == "Price3Dollar")
                SetEuroPrice(e.RowHandle, "Price3Euro", e.Value);
            else if (e.Column.FieldName == "FiyatExtra")
            {
                gvProduct.SetRowCellValue(e.RowHandle, "PriceDollar", DBNull.Value);
                gvProduct.SetRowCellValue(e.RowHandle, "PriceEuro", DBNull.Value);
                gvProduct.SetRowCellValue(e.RowHandle, "Price2Dollar", DBNull.Value);
                gvProduct.SetRowCellValue(e.RowHandle, "Price2Euro", DBNull.Value);
                gvProduct.SetRowCellValue(e.RowHandle, "Price3Dollar", DBNull.Value);
                gvProduct.SetRowCellValue(e.RowHandle, "Price3Euro", DBNull.Value);
            }

            gvProduct.CellValueChanged += gvProduct_CellValueChanged;
        }

        public void SetEuroPrice(int RowHandle, string TargetColumn, object value)
        {
            if (value != null && value != DBNull.Value)
                gvProduct.SetRowCellValue(RowHandle, TargetColumn, Utility.GetEuro((decimal)value));
            else
                gvProduct.SetRowCellValue(RowHandle, TargetColumn, DBNull.Value);
        }

        public List<int> changeds = new List<int>();

        public bool isIgnorable(int rowHandle)
        {
            if (rowHandle < 0)
                return true;
            else
                return !changeds.Contains(rowHandle);
        }


        public string GetComposition(string composition)
        {
            if (composition == "")
                return "";

            string comError = "";

            SortedDictionary<int, string> pairss = new SortedDictionary<int, string>();

            var pairs = new List<KeyValuePair<int, String>>();

            foreach (string part in composition.Split("-".ToCharArray()))
            {
                string h1 = part.Trim();
                if (h1.Contains("%"))
                {
                    string yuzde = h1.Split("%".ToCharArray())[0].Trim();
                    string kisaltma = h1.Split("%".ToCharArray())[1].Trim();
                    int yuzdelik = -1;
                    bool yuzdeMi = int.TryParse(yuzde, out yuzdelik);
                    if (!yuzdeMi)
                    {
                        comError = Language.Product.PercentageInteger;
                        break;
                    }
                    else if (Data.DB.Hammadde.Select("Kisaltma = '" + kisaltma + "'").Length == 0)
                    {
                        comError = kisaltma + Language.Product.IsNotValid;
                        break;
                    }
                    pairs.Add(new KeyValuePair<int, String>(-yuzdelik, kisaltma));
                }
                else
                {
                    if (Data.DB.Hammadde.Select("Kisaltma = '" + h1 + "'").Length == 0)
                    {
                        comError = h1 + Language.Product.IsNotValid;
                        break;
                    }

                    pairs.Add(new KeyValuePair<int, String>(1, h1));
                }
            }


            if (comError != "")
            {
                XtraMessageBox.Show(comError, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return "*";
            }
            else
            {
                string comp = "";
                foreach (KeyValuePair<int, string> pair in pairs.OrderBy(o => o.Key).ToList())
                {
                    if (pair.Key == 1)
                        comp += pair.Value + " - ";
                    else
                        comp += -pair.Key + "% " + pair.Value + " - ";
                }
                if (comp.EndsWith(" - "))
                    comp = comp.Substring(0, comp.Length - 3);

                return comp;
            }
        }


        void gvProduct_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            if (isIgnorable(e.RowHandle))
                return;

            //TODO: Product da bir değişiklik olunca, bu product ı içeren order ların editDate i now olarak set edilmeli

            int productId = -1;
            int.TryParse(gvProduct.GetRowCellValue(e.RowHandle, "ProductId").ToStringNN(), out productId);

            //if (productId > 0)
            {
                string Article;
                string Design;
                string Weight;
                string width;
                string composition;

                Article = gvProduct.GetRowCellValue(e.RowHandle, "Article").ToStringNN();
                Design = gvProduct.GetRowCellValue(e.RowHandle, "Design").ToStringNN();
                Weight = gvProduct.GetRowCellValue(e.RowHandle, "Weight").ToStringNN();
                width = gvProduct.GetRowCellValue(e.RowHandle, "Width").ToStringNN();
                composition = gvProduct.GetRowCellValue(e.RowHandle, "Composition").ToStringNN();

                string sameFilter = string.Format("ProductId <> {0} and isnull(Article,'') = '{1}' and isnull(Design,'') = '{2}' and isnull(Weight,'') = '{3}' and isnull(Width,'') = '{4}' and isnull(Composition,'') = '{5}'", productId, Article, Design, Weight, width, composition);
                DataRow[] sameProduct = Data.DB.Product.Select(sameFilter);

                string newComp = GetComposition(composition);
                if (!newComp.StartsWith("*"))
                    gvProduct.SetRowCellValue(e.RowHandle, "Composition", newComp);
                else
                {
                    e.Valid = false;
                    return;
                }

                if (sameProduct.Length > 0)
                {
                    ShowError("Aynı artikel tanımlı.");
                    e.Valid = false;
                    return;
                }
                else
                {
                    //e.Valid = true;
                    DialogResult result = Ask("Değişiklikler kaydedilecek." + " (SatırNo:" + e.RowHandle.ToString() + ")");
                    e.Valid = (result == DialogResult.OK);
                }
            }
        }

        void AddFilter(string colName, string filter)
        {
            if (filter == "")
                return;

            if (filter.StartsWith("*"))
            {
                filter = filter.Replace("*", "");
                filters.Add(string.Format("Contains([{0}] , '{1}')", colName, filter));
            }
            else
                filters.Add(string.Format("StartsWith([{0}] , '{1}')", colName, filter));
        }

        List<string> filters = new List<string>();

        void txtArticle_EditValueChanged(object sender, EventArgs e)
        {
            filters = new List<string>();

            AddFilter("ProductId", txtProductId.Text);

            AddFilter("Article", txtArticle.Text);
            AddFilter("Design", txtDesign.Text);
            AddFilter("Weight", txtWeight.Text);
            AddFilter("Article", txtArticle.Text);

            AddFilter("ToleranceWeight", txtWeightTol.Text);
            AddFilter("Width", txtWidth.Text);
            AddFilter("ToleranceWidth", txtWidthTol.Text);
            AddFilter("Composition", txtComp.Text);
            AddFilter("ToleranceComposition", txtCompTol.Text);
            AddFilter("PriceDollar", txtDollar.Text);
            AddFilter("PriceEuro", txtEuro.Text);

            gvProduct.ActiveFilterString = String.Join(" and ", filters.ToArray());
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            string composition = txtComp.EditValue.ToStringNN();

            string newComp = GetComposition(composition);
            if (!newComp.StartsWith("*"))
                txtComp.EditValue = newComp;
            else
                return;

            string sameFilter = string.Format("isnull(Article,'') = '{0}' and isnull(Design,'') = '{1}' and isnull(Weight,'') = '{2}' and isnull(Width,'') = '{3}' and isnull(Composition,'') = '{4}'", txtArticle.EditValue, txtDesign.EditValue, txtWeight.EditValue, txtWidth.EditValue, txtComp.EditValue);
            DataRow[] sameProduct = Data.DB.Product.Select(sameFilter);


            if (sameProduct.Length > 0)
            {
                XtraMessageBox.Show(Language.Product.SameProduct, Language.Uyari, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                decimal dollar = 0;
                decimal.TryParse(txtDollar.EditValue.ToStringNN(), out dollar);

                decimal Euro = 0;
                decimal.TryParse(txtEuro.EditValue.ToStringNN(), out Euro);

                if (dollar > 0 && Euro == 0)
                {
                    Euro = Utility.GetEuro(dollar);
                }

                AkerDB.ProductRow drProduct = Data.DB.Product.NewProductRow();

                drProduct.Article = txtArticle.EditValue.ToStringNN();
                drProduct.Weight = txtWeight.EditValue.ToStringNN();
                drProduct.ToleranceWeight = txtWeightTol.EditValue.ToStringNN();
                drProduct.Width = txtWidth.EditValue.ToStringNN();
                drProduct.ToleranceWidth = txtWidthTol.EditValue.ToStringNN();
                drProduct.Composition = txtComp.EditValue.ToStringNN();
                drProduct.ToleranceComposition = txtCompTol.EditValue.ToStringNN();
                drProduct.Design = txtDesign.EditValue.ToStringNN();
                drProduct.PriceDollar = dollar;
                drProduct.PriceEuro = Euro;

                drProduct.Price2Dollar = dollar;
                drProduct.Price2Euro = Euro;

                drProduct.Price3Dollar = dollar;
                drProduct.Price3Euro = Euro;

                drProduct.ModifiedBy = AppSession.UserInfo.UserId;
                drProduct.ModifiedOn = DateTime.Now;

                Data.DB.Product.AddProductRow(drProduct);
                Data.SaveProduct(drProduct);


            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            foreach (Control ctrl in splitter.Panel1.Controls)
            {
                if (ctrl.GetType() == typeof(TextEdit))
                    ((TextEdit)ctrl).Text = "";
            }

            gvProduct.ActiveFilterString = "";
        }

        private void btnSelectVisible_Click(object sender, EventArgs e)
        {
            gvProduct.BeginUpdate();

            foreach (DataRow item in Data.DB.Product.Rows)
            {
                item["Select"] = false;
                item["Order"] = DBNull.Value;
            }

            for (int i = 0; i < gvProduct.RowCount; i++)
            {
                //int rowHandle = gvProduct.GetVisibleRowHandle(i);
                ToggleSelection(i);
            }

            gvProduct.EndUpdate();
        }

        private void chkPrices_EditValueChanged(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            string selection = chkPrices.EditValue.ToString();
            List<string> items = selection.Replace(" ", "").Split(",".ToCharArray()).ToList();

            gvProduct.SetVisibleIndex(orderedColumns);

            gvProduct.Columns["PriceDollar"].Visible = gvProduct.Columns["PriceEuro"].Visible = items.Contains("1");
            gvProduct.Columns["Price2Dollar"].Visible = gvProduct.Columns["Price2Euro"].Visible = items.Contains("2");
            gvProduct.Columns["Price3Dollar"].Visible = gvProduct.Columns["Price3Euro"].Visible = items.Contains("3");

            this.Cursor = Cursors.Default;
        }

        private void btnUpdatePrices_Click(object sender, EventArgs e)
        {
            using (PriceUpdater pu = new PriceUpdater())
            {
                if (pu.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Data.DB.Hammadde.Clear();
                    Data.TAM.HammaddeTableAdapter.Fill(Data.DB.Hammadde);
                    Data.RefreshData();
                }
            }
        }

        private void btnMaliyet_Click(object sender, EventArgs e)
        {
            using (PriceUpdaterMaliyet pu = new PriceUpdaterMaliyet())
            {
                if (pu.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.Cursor = Cursors.WaitCursor;
                    Data.RefreshData();
                    this.Cursor = Cursors.Default;

                    Data.TAM.SettingTableAdapter.Fill(Data.DB.Setting);
                    string ekstraCarpan = Data.DB.Setting.FindBySettingId(16).Value;
                    gvProduct.SetCaptions("FiyatExtra:Fiyat* (" + ekstraCarpan + ")");
                }
            }
        }

        private void Products_Shown(object sender, EventArgs e)
        {
            txtArticle.Focus();
        }

    }
}